package com.kcwl.carrier.infrastructure.advice;

import com.kcwl.carrier.infrastructure.annotation.IdentityAuth;
import com.kcwl.carrier.infrastructure.enums.CarrierUseErrorCodeEnum;
import com.kcwl.carrier.infrastructure.exceptions.CarrierUserException;
import com.kcwl.ddd.application.constants.IdentityTypeEnum;
import com.kcwl.ddd.infrastructure.api.CommonCode;
import com.kcwl.ddd.infrastructure.exception.BizException;
import com.kcwl.ddd.infrastructure.session.SessionContext;
import com.kcwl.ddd.infrastructure.session.SessionData;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @author 刘旭超
 * @date 2022年07月14日 10:00
 * @Description 需要身份类型拦截的接口校验
 */
@Component
@Aspect
@Slf4j
public class IdentityAuthAdvice {

    @Pointcut("@annotation(com.kcwl.carrier.infrastructure.annotation.IdentityAuth)")
    public void point() {
    }

    @Before("point()")
    public void identityCheck(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getMethod().getName();
        IdentityAuth annotation = signature.getMethod().getAnnotation(IdentityAuth.class);
        IdentityTypeEnum[] value = annotation.value();
        SessionData sessionData = SessionContext.getSessionData();
        if (sessionData == null) {
            throw new BizException(CommonCode.UN_LOGIN.getCode(), CommonCode.UN_LOGIN.getDescription());
        }
        Integer identityType = sessionData.getIdentityType();
        log.info("【身份类型拦截】method:{}, identityType:{}, userId:{}", methodName, identityType, sessionData.getUserId());
        for (IdentityTypeEnum identityTypeEnum : value) {
            if (identityTypeEnum.getCode().equals(identityType)) {
                return;
            }
        }
        throw new CarrierUserException(CarrierUseErrorCodeEnum.IDENTITY_TYPE_ERROR);
    }
}
